package org.m2acsi.control;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.List;
import javax.annotation.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.Part;
import org.m2acsi.boundary.DocumentEJB;
import org.m2acsi.boundary.DownloadEJB;
import org.m2acsi.boundary.FileManager;
import org.m2acsi.entities.Document;
import org.m2acsi.entities.Download;
import org.m2acsi.entities.Task;
import org.m2acsi.entities.Upload;
import org.m2acsi.utils.Security;

@Named
@RequestScoped
@ManagedBean
public class FileUploadBean extends BaseBean implements Serializable {

    private Part uploadedFile;
    private FileManager fm = new FileManager("Files");
    private Document document;
    private long taskId;

    @Inject
    private DocumentEJB documentEjb;
    @Inject
    private DownloadEJB downloadEJB;

    public FileUploadBean() {
        super();
    }

    public Part getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(Part uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public long getTaskId() {
        return taskId;
    }

    public void setTaskId(long taskId) {
        this.taskId = taskId;
    }

    public void upload() {
        if (uploadedFile != null && uploadedFile.getSize() != 0) {
            String idTaskString = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
            Task tmpTask = Security.taskSecurityCheck(idTaskString, getAuthenticatedUser(), taskEjb, this);
            taskId = tmpTask.getId();
            if (tmpTask.isFinished()) {
                try {
                    InputStream is = uploadedFile.getInputStream();

                    //Get file name
                    String headerContent = uploadedFile.getHeader("content-disposition");
                    String nameFile = headerContent.substring((headerContent.substring(0, headerContent.length() - 1)).lastIndexOf("\"") + 1, headerContent.length() - 1);

                    document = fm.uploadFile(is, nameFile);
                    Upload upload = new Upload(getAuthenticatedUser(), document);
                    document.setUpload(upload);

                    document.setTask(tmpTask);
                    List<Document> tmpTaskDocs = tmpTask.getDocuments();
                    tmpTaskDocs.add(document);
                    tmpTask.setDocuments(tmpTaskDocs);
                    List<Upload> lUpload = getAuthenticatedUser().getUploads();
                    lUpload.add(upload);
                    getAuthenticatedUser().setUploads(lUpload);

                    documentEjb.save(document);
                    taskEjb.update(tmpTask);
                    redirectWithMessage("/faces/user/task.xhtml?id=" + taskId, document.getName() + " has been uploaded.");
                } catch (IOException ex) {
                    FacesContext.getCurrentInstance().addMessage("form:file", new FacesMessage("An error occured while trying to save this file."));
                }
            } else {
                hackRedirect("try to edit a closed task.");
            }
        } else {
            FacesContext.getCurrentInstance().addMessage("form:file", new FacesMessage("You have not selected any file."));
        }
    }

    public void download() {
        document = Security.documentSecurityCheck(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"), getAuthenticatedUser(), documentEjb, this);
        Download d = new Download();
        d.setDocument(document);
        d.setUser(getAuthenticatedUser());
        downloadEJB.save(d);

        List<Download> downloads = document.getDownloads();
        downloads.add(d);
        document.setDownloads(downloads);
        documentEjb.update(document);

        fm.getFile(document.getMongoId());
    }
}
